package socket.example4;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author lhn
 * @date 2024-04-25 15:57
 */

public class StreamUtils {

    /*
    *
    * @author lihaonan
    * @date 2024/4/25 16:01
     * @param inputStream
     * @return byte[]
     * 将输入流转换成byte[],即可以把文件的内容读入到byte[]
    */
    public static byte[] streamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];  //字节数组
        int len;
        //循环读取
        while((len = inputStream.read(bytes)) != -1) {
            //把读取的字节数组写入到流中
            byteArrayOutputStream.write(bytes, 0, len);
        }
        byte[] array = byteArrayOutputStream.toByteArray(); //然后将byteArrayOutputStream转成字节数组
        byteArrayOutputStream.close();
        return array;
    }
}
